package com.xbongbong.pro.service.toolbox.smartsettings.help;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.smartsettings.enums.AiAssistantPushTypeEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartSettingsFieldEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.AiAssistantModel;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.FeeCompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @description: 智能助手帮助类
 * @Author: hongxiao
 * @date: 2019-05-24 16:35
 * @since v1.0
 */
@Component
public class SmartSettingsHelp {
    private static final Logger LOG = LoggerFactory.getLogger(SmartSettingsHelp.class);
    @Resource
    private AiAssistantModel aiAssistantModel;
    @Resource
    private FeeCompanyModel feeCompanyModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PaasAppModel paasAppModel;

    /**
     * 获取占位符
     *
     * @param saasMark     saas/paas标识枚举
     * @param businessType 业务类型
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-24 16:36
     * @since
     * @version
     */
    public String getPlaceHolder(Integer saasMark, Integer businessType) {
        String placeHoler = "";
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            placeHoler = refTypeEnum.getName();
        }
        return placeHoler;
    }


    /**
     * 设置字段对应的智能助手个数：智能助手触发条件只有一个的字段
     * @param corpid 公司id
     * @param formId 表单id
     * @param explainList 字段解释列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-30 09:16
     * @since v1.0
     * @version v1.0
     */
    public void setSsNumForExplain(String corpid, Long formId, List<FieldAttrEntity> explainList) {

        List<AiAssistantEntity> list = aiAssistantModel.getListByOneCondition(corpid, formId);
        if(list.isEmpty()) {
            return;
        }
        Map<String, Integer> attrNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for(AiAssistantEntity entity : list) {
            List<ConditionsEntityExt> conditionList = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
            String alias = conditionList.get(0).getAttr();
            // attr转化为表单字段的attr(为空时，非表单字段的触发条件）
            String formAttr = SmartSettingsFieldEnum.getFormAttr(alias);
            if(formAttr == null) {
                formAttr = alias;
            }
            if(StringUtil.isEmpty(formAttr)) {
                continue;
            }

            int num = 1;
            if(attrNumMap.containsKey(formAttr)) {
                num = num + attrNumMap.get(formAttr);
            }
            attrNumMap.put(formAttr, num);
        }
        // 没有对应的表单字段
        if(attrNumMap.isEmpty()) {
            return;
        }
        if (Objects.equals("ding3ba53ee58fce70da4ac5d6980864d335", corpid)) {
            LOG.info("smartSettingsNum:" + JSON.toJSONString(attrNumMap));
        }
        for(FieldAttrEntity entity : explainList) {
            String attr = entity.getAttr();
            if(attrNumMap.containsKey(attr)) {
                entity.setSmartSettingsNum(attrNumMap.get(attr));
            }
        }
    }

    /**
     * 是否有智能助手
     *
     * @param corpid 公司id
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-12-09 10:32
     * @since
     * @version
     */
    public boolean hasMenu(String corpid) {
        // 前缀
        String filePrefix = RedisConstant.KEY_COMPANY_CONFIG;
        // 所有公司的，不用拼接corpid
        String aiAssistantWhiteKey = RedisPrefixConstant.AI_AAAISTANT_WHITE_KEY;
        // 取redis-value
        String aiAssistantWhiteValue = paasRedisHelper.getValue(filePrefix, aiAssistantWhiteKey);

        // 智能助手白名单
        if (Objects.isNull(aiAssistantWhiteValue)) {
            CompanyConfigEntity aiAssistantWhiteConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.AI_ASSISTANT_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            if (Objects.isNull(aiAssistantWhiteConfig)) {
                aiAssistantWhiteValue = CompanyConfigEnum.AI_ASSISTANT_WHITE.getValue();
            } else {
                aiAssistantWhiteValue = aiAssistantWhiteConfig.getConfigValue();
            }
            paasRedisHelper.setValue(RedisConstant.KEY_COMPANY_CONFIG, aiAssistantWhiteKey, aiAssistantWhiteValue, TimeConstant.TEN_MINUTE_DURATION);
        }

        // 智能助手白名单
        List<String> aiAssistantWhite = JsonHelperUtil.parseArray(aiAssistantWhiteValue, String.class);
        boolean hasAssistantWhite = !aiAssistantWhite.isEmpty();
        if ((hasAssistantWhite && !aiAssistantWhite.contains(corpid))) {
            return false;
        }

        return true;
    }

    /**
     * 　其他推送类型：仓库预警、产品保质期、四个待（待采购、待生产、待出库、待入库）
     *
     * @param entity 智能助手实体
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-12-03 19:56
     * @version v1.0
     * @since v1.0
     */
    public AiAssistantPushTypeEnum otherPush(AiAssistantEntity entity) {
        AiAssistantPushTypeEnum pushTypeEnum = null;
        List<ConditionsEntityExt> triggerCondition = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
        for (ConditionsEntityExt entityExt : triggerCondition) {
            SmartSettingsFieldEnum ssFieldEnum = SmartSettingsFieldEnum.getFieldTypeEnum(entityExt.getFieldType());
            if (Objects.isNull(ssFieldEnum)) {
                continue;
            }
            switch (ssFieldEnum) {
                case PRODUCT_STOCK_LOWER_WARNING:
                case PRODUCT_STOCK_UPPER_WARNING:
                    pushTypeEnum = AiAssistantPushTypeEnum.PRODUCT_STOCK_WARNING_PUSH;
                    break;
                case PRODUCT_EXPIRE_WARNING:
                    pushTypeEnum = AiAssistantPushTypeEnum.PRODUCT_STOCK_GUARANTEE_PUSH;
                    break;
                case WAIT_PURCHASE:
                    pushTypeEnum = AiAssistantPushTypeEnum.WAIT_PURCHASE_PUSH;
                    break;
                case WAIT_PRODUCTION_ORDER:
                    pushTypeEnum = AiAssistantPushTypeEnum.WAIT_PRODUCE_PUSH;
                    break;
                case WAIT_OUTSTOCK:
                    pushTypeEnum = AiAssistantPushTypeEnum.WAIT_OUTSTOCK_PUSH;
                    break;
                case WAIT_INSTOCK:
                    pushTypeEnum = AiAssistantPushTypeEnum.WAIT_INSTOCK_PUSH;
                    break;
                default:
                    break;
            }
        }
        return pushTypeEnum;
    }
}
